import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { UserEntity } from './entities/user.entity'
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { BaseService } from '@/common/base/service';
import { QueryUserDto } from './dto/query-user.dto';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class UserService extends BaseService<UserEntity> {
  constructor(
    @InjectRepository(UserEntity) private usersRepo: Repository<UserEntity>,
  ) {
    super(usersRepo)
  }
  // //创建、注册用户
  async create(dto: CreateUserDto) {
    const exist = await this.usersRepo.findOne({ where: { account: dto.account } })
    if (exist) throw new BadRequestException('账号已存在');

    //对密码进行加密处理
    const hashPwd = await bcrypt.hash(dto.password, 10)
    dto.password = hashPwd
    const user = this.usersRepo.create(dto)
    const saved = await this.usersRepo.save(user)
    const { password, ...reset } = saved
    return reset
  }


  // 查询列表（分页查询）
  async findAll(query) {
    //ASC正序、DESC倒序
    return await this.paginate(query, ['username'], [], { id: 'DESC' });
  }

  // 查询单个
  async findOne(id: number) {
    const user = await this.usersRepo.findOne({ where: { id } });
    if (!user) throw new NotFoundException('用户不存在');
    const { password, ...reset } = user
    return reset;
  }


  // 更新
  async update(id: number, dto) {
    const user = await this.usersRepo.findOne({ where: { id } })
    if (!user) throw new NotFoundException('用户不存在');

    await this.usersRepo.update(id, dto)
    return this.findOne(id)
  }

  //删除
  async remove(id: number) {
    const user = await this.usersRepo.findOne({ where: { id } })
    if (!user) throw new NotFoundException(`未找到id为 ${id} 的用户`);
    await this.usersRepo.delete(id);
    return { message: '用户已删除' };
  }

  //  通过账号查找密码
  async findByAccount(account: string) {
    return await this.usersRepo.findOne({ where: { account } })
  }
}
